using StandardRobotppTool.Views;
using System.Windows.Input;

namespace StandardRobotppTool.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        private object _currentPage;
        public object CurrentPage
        {
            get => _currentPage ?? throw new InvalidOperationException("CurrentPage is not initialized");
            set
            {
                _currentPage = value;
                OnPropertyChanged();
            }
        }

        private readonly Page_Info _infoPage = new Page_Info();
        private readonly Page_DataWave _dataWavePage = new Page_DataWave();
        private readonly Page_Control _controlPage = new Page_Control();

        public ICommand NavigateCommand => new RelayCommand<string>(ExecuteNavigate);

        public MainViewModel()
        {
            _currentPage = _infoPage;
            // 默认显示 InfoPage
            CurrentPage = _infoPage;
        }


        private void ExecuteNavigate(string pageKey)
        {
            switch (pageKey)
            {
                case "Page_Info":
                    CurrentPage = _infoPage;
                    break;
                case "Page_DataWave":
                    CurrentPage = _dataWavePage;
                    break;
                case "Page_Control":
                    CurrentPage = _controlPage;
                    break;
                default:
                    CurrentPage = _infoPage; // 默认页面
                    break;
            }
        }
    }

    public class RelayCommand<T> : ICommand
    {
        private readonly Action<T> _execute;
        private readonly Func<T, bool>? _canExecute;

        public RelayCommand(Action<T> execute, Func<T, bool>? canExecute = null)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
            _canExecute = canExecute;
        }

        public bool CanExecute(object? parameter)
        {
            // 处理值类型的空值问题
            if (parameter is null && default(T) is not null)
            {
                return false;
            }
            return _canExecute == null || _canExecute((T)parameter!);
        }

        public void Execute(object? parameter)
        {
            if (parameter is null && default(T) is not null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }
            _execute((T)parameter!);
        }

        public event EventHandler? CanExecuteChanged
        {
            add => CommandManager.RequerySuggested += value;
            remove => CommandManager.RequerySuggested -= value;
        }
    }
}